package cn.ekuma.android.ui.tree;

import java.util.ArrayList;
import java.util.List;
 
import android.content.Context;
import android.graphics.Color;
import android.widget.ListView;

 
 public class TreeView extends ListView {
    
     private final int SELECTED_TOP = 150;
 
     private TreeCallBack callBack;

     private TreeAdapter adapter;
 

    public TreeView(Context context) {
        super(context); 
    }
    
    public void setTreeAdapter(TreeAdapter adapter){
    	this.adapter=adapter;
    	callBack=adapter.getCallBack();
    	this.setAdapter(adapter);
        this.setCacheColorHint(Color.parseColor("#00000000"));
        this.setVerticalFadingEdgeEnabled(false);
//      this.setOnTouchListener(onTouch);
    }
     
     public void setSelectedItemByTag(Object tag) {
        checkedItemByTag(adapter.getElements(), tag);
        adapter.setItems(new ArrayList<TreeElement>());
        adapter.createItems(adapter.getElements());
        adapter.notifyDataSetChanged();
        if (adapter.getSelectedPosition() != -1)
            TreeView.this.setSelectionFromTop(adapter.getSelectedPosition(), SELECTED_TOP);
     }

     private void checkedItemByTag(List<TreeElement> es, Object tag) {
         for (TreeElement e : es) {
            if (e.hasChildren()) {
                checkedItemByTag(e.getChildren(), tag);
             } else {
                if (callBack.equalByTag(tag, e.getTag())) {
                    setParentExpend(e.getParent());
                    e.setSelected(true);
                 } else {
                    e.setSelected(false);
                }
             }
         }
     }
 
     private void setParentExpend(TreeElement e) {
         e.setExpanded(true);
         if (e.getParent()!= null)
             setParentExpend(e.getParent());
     }
 }
